using System;
using System.Collections.ObjectModel;
using System.Linq;
using DockComponent.Base;
using ReactiveUI;
using NLog;

namespace DockTemplate.Services;

public class ErrorService : ReactiveObject
{
    private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
    private readonly ObservableCollection<ErrorEntry> _errors = new();

    public ObservableCollection<ErrorEntry> Errors => _errors;
    
    public ErrorService()
    {
        // Subscribe to single error messages from NLog via MessageBus
        MessageBus.Current.Listen<ErrorMessage>()
            .Subscribe(errorMsg =>
            {
                if (errorMsg.Entry != null)
                {
                    _errors.Insert(0, errorMsg.Entry);
                    UpdateCounts();
                }
            });

        // Subscribe to batched error messages from LogBatchingService
        MessageBus.Current.Listen<BatchedErrorMessage>()
            .Subscribe(batchedMsg =>
            {
                if (batchedMsg.Entries?.Length > 0)
                {
                    foreach (var entry in batchedMsg.Entries)
                    {
                        Avalonia.Threading.Dispatcher.UIThread.Post(() =>
                        {
                            _errors.Insert(0, entry);
                        }, Avalonia.Threading.DispatcherPriority.Background);
                    }
                    UpdateCounts();
                }
            });
    }

    private void UpdateCounts()
    {
        this.RaisePropertyChanged(nameof(ErrorCount));
        this.RaisePropertyChanged(nameof(WarningCount));
    }

    public int ErrorCount => _errors.Count(e => e.Level == "Error");
    public int WarningCount => _errors.Count(e => e.Level == "Warning");

    public void Clear()
    {
        _errors.Clear();
        this.RaisePropertyChanged(nameof(ErrorCount));
        this.RaisePropertyChanged(nameof(WarningCount));
    }


}